import proto from "../../../proto/proto";
import { RoomBase } from "../base/RoomBase";
import { GameRoomPlayer } from "./GameRoomPlayer";



export class GameRoom extends RoomBase<GameRoomPlayer> {


    syncHandle: any = null;
    inputDatas: proto.FrameData[] = [];
    frameId: number = 0;

    onInit(): void {
    }

    onDestroy(): void {

    }

    onStart(): void {

    }

    addPlayer(userId: number): GameRoomPlayer {
        if (!this.hasPlayer(userId)) {
            const player = new GameRoomPlayer(userId)
            player.setChair(this.players.length)
            this.players.push(player);
            
        }
        return this.getPlayer(userId) as GameRoomPlayer;
    }

    onMsg(userId: number, cmd: number, reqWrap: proto.ReqWrap, reqData: any): void {

    }

    /**
     * 广播游戏开始
     */
    roomtStart(): void {
        this.broadcast(proto.SubGame100.L2B_RoomStart)
        this.frameId = 0
        if (this.syncHandle)
            clearInterval(this.syncHandle)
        this.syncHandle = setInterval(() => {
            this.frameId++
            if (this.inputDatas.length > 0) {
                const msgData = new proto.MSG_L2B_SubGame100_PlayerInput()
                for (let i = 0; i < this.players.length; i++) {
                    const player = this.players[i]
                    console.log(`frameId:${this.frameId}---userId:${player.userId}`);
                    //合并移动数据
                    const inputMoveDatas = this.inputDatas.filter(a => a.type == 1 && a.userid == player.userId)
                    const initialAccumulator = { deltaX: 0, deltaY: 0 };
                    const { deltaX, deltaY } = inputMoveDatas.reduce((accumulator, current) => {
                        return {
                            deltaX: accumulator.deltaX + current.deltaX,
                            deltaY: accumulator.deltaY + current.deltaY
                        };
                    }, initialAccumulator);
                    msgData.datas.push({
                        userid: player.userId,
                        deltaX: deltaX,
                        deltaY: deltaY,
                        key: 0,
                        type: 1
                    })
                }
                this.inputDatas = []
                this.broadcast(proto.SubGame100.L2B_PlayerInput, proto.MSG_L2B_SubGame100_PlayerInput.encode(msgData).finish())
            }
            else {
                const msgData = proto.MSG_L2B_SubGame100_PlayerInput.encode({
                    frameId: this.frameId,
                }).finish()
                this.broadcast(proto.SubGame100.L2B_PlayerInput, msgData)
            }

        }, 50)
    }
}